import { resolve } from 'node:path'
import type { ConfigEnv, UserConfig } from 'vite'
import { defineConfig, loadEnv } from 'vite'
import { createVitePlugins } from './build/plugins'
import resetEnvParams from './build/resetEnv'

// @see: https://vitejs.dev/config/
export default defineConfig((envConf: ConfigEnv): UserConfig => {
  // eslint-disable-next-line node/prefer-global/process
  const root = process.cwd()
  const env = loadEnv(envConf.mode, root) as ImportMetaEnv
  // 构建时修改public/env.js里的变量
  resetEnvParams(env, resolve(__dirname, './public/config.js'))
  const { VITE_APP_BASE_URL, VITE_OUTPUT_DIR, VITE_OPEN_PROXY, VITE_DROP_CONSOLE } = env
  return {
    base: './',
    root,
    server: {
      host: true,
      port: 8083,
      proxy: {
        '/dev-api': {
          target: VITE_APP_BASE_URL,
          changeOrigin: !!VITE_OPEN_PROXY,
          secure: false,
          rewrite: p => p.replace(/^\/dev-api/, ''),
        },
      },
    },
    plugins: createVitePlugins(envConf),
    resolve: {
      alias: {
        '@': resolve(__dirname, './src'),
      },
    },
    css: {
      preprocessorOptions: {
        scss: {
          additionalData: '@import "@/styles/index.scss";',
        },
      },
    },
    esbuild: {
      pure: VITE_DROP_CONSOLE === 'true' ? ['console.log', 'console.info', 'console.warn', 'console.error', 'console.debug', 'debugger'] : [],
    },
    build: {
      outDir: VITE_OUTPUT_DIR,
      minify: 'esbuild',
      // 禁用 gzip 压缩大小报告，可略微减少打包时间
      reportCompressedSize: false,
      // 规定触发警告的 chunk 大小
      chunkSizeWarningLimit: 1000,
      rollupOptions: {
        output: {
          manualChunks: {
            vues: ['vue', 'vue-router', 'pinia', 'pinia-plugin-persistedstate', 'axios'],
            elementPlus: ['element-plus'],
            icons: ['@element-plus/icons-vue'],
            tools: ['moment', 'js-md5', 'qs'],
          },
        },
      },
    },
  }
})
